package com.pig4cloud.pig.module.service.mer.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.yilianprint.LAVApi;
import com.pig4cloud.pig.common.core.yilianprint.Methods;
import com.pig4cloud.pig.module.api.entity.mer.MerPrinter;
import com.pig4cloud.pig.module.mapper.mer.MerPrinterMapper;
import com.pig4cloud.pig.module.service.mer.IMerPrinterService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 餐饮商家打印机列Service业务层处理
 *
 * @author ruoyi
 * @date 2023-05-05
 */
@Service
public class MerPrinterServiceImpl extends ServiceImpl<MerPrinterMapper, MerPrinter> implements IMerPrinterService {

	@Resource
	private MerPrinterMapper merPrinterMapper;

	@Override
	public String getPrinterAccessToken(int printId) {
		String access_token = "";
		MerPrinter printer = merPrinterMapper.selectById(printId);
		if(printer != null){
			if(StrUtil.isEmpty(printer.getAccessToken())){//
				JSONObject jsonObject = getAccessTokenHttp(printer);
				String error = "", refresh_token = "";
				if(jsonObject != null){
					error = jsonObject.getStr("error");
					if(error.equals("0")){
						access_token = jsonObject.getJSONObject("body").getStr("access_token");
						refresh_token = jsonObject.getJSONObject("body").getStr("refresh_token");
						printer.setAccessToken(access_token);
						printer.setRefreshToken(refresh_token);
						printer.setRefreshTokenTime(new Date());
						merPrinterMapper.updateById(printer);
					}
				}
			}else{
				access_token = printer.getAccessToken();
				Date lastTokenTime = printer.getAccessTokenTime();
				Date valideTime = DateUtils.getAfterSecondsByOld(lastTokenTime, 5 * 60 * 60);
				if(new Date().getTime() > valideTime.getTime() ){
					JSONObject jsonObject = getAccessTokenHttp(printer);
					String error = "", refresh_token = "";
					if(jsonObject != null){
						error = jsonObject.getStr("error");
						if(error.equals("0")){
							access_token = jsonObject.getJSONObject("body").getStr("access_token");
							refresh_token = jsonObject.getJSONObject("body").getStr("refresh_token");
							printer.setAccessToken(access_token);
							printer.setRefreshToken(refresh_token);
							printer.setRefreshTokenTime(new Date());
							merPrinterMapper.updateById(printer);
						}
					}
				}
			}
		}
		return access_token;
	}


	private JSONObject getAccessTokenHttp(MerPrinter printer){
		JSONObject jsonObject = new JSONObject();
		long timestamp = System.currentTimeMillis() / 1000;
		String sign = LAVApi.getSin(printer.getClientId() , printer.getClientAppKey(),timestamp);
//                {"error":"0","error_description":"success","body":{"access_token":"3c06083428f34d1d979df5761b63bfae","refresh_token":"97cfef81f13a40f08781583fae32f620","machine_code":"","expires_in":2592000,"scope":"all"}}
		String result = Methods.getFreedomToken(printer.getClientId() ,sign,String.valueOf(timestamp));
//                result = " {\"error\":\"0\",\"error_description\":\"success\",\"body\":{\"access_token\":\"3c06083428f34d1d979df5761b63bfae\",\"refresh_token\":\"97cfef81f13a40f08781583fae32f620\",\"machine_code\":\"\",\"expires_in\":2592000,\"scope\":\"all\"}}";
		if(result != null && !result.equals("")){
			//{'error':'0','error_description':'success','body':{'access_token':'xxxx','refresh_token':'xxxx','expires_in':2592000,'scope':'all'}}
			jsonObject = JSONUtil.parseObj(result);
			if(jsonObject!=null){
//                error = jsonObject.getStr("error");
//                if(error.equals("0")){
//                    access_token = jsonObject.getJSONObject("body").getStr("access_token");
//                    refresh_token = jsonObject.getJSONObject("body").getStr("refresh_token");
//                    printer.setAccessToken(access_token);
//                    printer.setRefreshToken(refresh_token);
//                    printer.setRefreshTokenTime(new Date());
//                    merPrinterMapper.updateById(printer);
//                }
			}
		}
		return jsonObject;
	}


	@Override
	public String getPrinterRefreshToken(int printId,int isReset) {
		String access_token = "";
		MerPrinter printer = merPrinterMapper.selectById(printId);
		if(printer!= null){
			if(StrUtil.isEmpty(printer.getRefreshToken()) || isReset == 1){//
				long timestamp = System.currentTimeMillis() / 1000;
				String sign = LAVApi.getSin(printer.getClientId() , printer.getClientAppKey(),timestamp);
				String result = Methods.getFreedomToken(printer.getClientId() ,sign,String.valueOf(timestamp));
				if(result != null && !result.equals("")){
					JSONObject jsonObject = JSONUtil.parseObj(result);
					String error = "", refresh_token = "";
					if(jsonObject!=null){
						error = jsonObject.getStr("error");
						if(error.equals("0")){
							access_token = jsonObject.getJSONObject("body").getStr("access_token");
							refresh_token = jsonObject.getJSONObject("body").getStr("refresh_token");
							printer.setAccessToken(access_token);
							printer.setAccessTokenTime(new Date());
							printer.setRefreshToken(refresh_token);
							printer.setRefreshTokenTime(new Date());
							merPrinterMapper.updateById(printer);
						}
					}
				}
			}else{
				access_token = printer.getAccessToken();
			}
		}
		return access_token;
	}

}
